package us.gaaoc.framework.webapp.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.hibernate.Session;
import org.pdfbox.exceptions.COSVisitorException;
import org.pdfbox.util.PDFMergerUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import us.gaaoc.framework.dao.ModelFacade;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.util.io.FileUtility;

@Component
public class ViewAllPdfController {

	protected File mergeDocuments(CaseRecord cr,List<Documents> documents) throws IOException, COSVisitorException
	{
		PDFMergerUtility mergePdf = new PDFMergerUtility();
		
		for(Documents d : documents)
		{							
			mergePdf.addSource(d.getContentAsFileHandle());					
		}
		
		File f = File.createTempFile(cr.getUuid() + "_", ".temp.pdf");
		mergePdf.setDestinationFileName(f.getAbsolutePath());
		mergePdf.mergeDocuments();
		return f;
	}
	
	
	//TODO: move to modelFacade
	protected List<Documents> getImportedDocuments(CaseRecord cr)
	{
		return modelFacade.getSession().createQuery("from Documents where caseRecord = :cr and status.code = 2")
			.setParameter("cr",cr)
			.list();
	}
	
	@Autowired
	ModelFacade modelFacade;
	
	@Transactional
	public String viewAll() throws IOException, COSVisitorException { 
		
		String caseUuid;
		CaseRecord cr;
		HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
		FacesContext context = FacesContext.getCurrentInstance();
		{									
			Map sessionMap = context.getExternalContext().getSessionMap();
			caseUuid = (String) sessionMap.get("caseUuid");
			cr = modelFacade.findCaseRecordById(caseUuid,"");
		}
													
		File f = mergeDocuments(cr, getImportedDocuments(cr));			
		String ret = FileUtility.streamReportToBrowser(res,cr.getFilingNumber() + "_ImportedDocuments.pdf",IOUtils.toByteArray(new FileInputStream(f)));		
		if(ret.equals("stay")) context.responseComplete();		
		return ret;
	}
	
	
}
